import Konva from 'konva'
import { useEffect, useRef, useState } from 'react'
import { Group, Layer, Line, Stage, Transformer } from 'react-konva'

export default function View() {
  // pen
  const [tool, setTool] = useState('pen')
  const [lines, setLines] = useState([])
  const isDrawing = useRef(false)
  const stageRef = useRef<Konva.Stage>(null)
  const groupRef = useRef<Konva.Group>(null)

  const handleMouseDown = e => {
    isDrawing.current = true
    const point = e.target.getStage().getPointerPosition()

    // 对变换矩阵求逆
    const groupTransform = groupRef.current.getAbsoluteTransform()
    const inverseTransform = groupTransform.copy().invert()
    const startPoint = inverseTransform.point({ x: 0, y: 0 })

    const scaleX = 1 / groupRef.current.scaleX()
    const scaleY = 1 / groupRef.current.scaleY()
    const skewX = -groupRef.current.skewX()
    const skewY = -groupRef.current.skewY()
    const rotation = -groupRef.current.rotation()

    // const startPoint = inverseTransform.point({ x: pos.x, y: pos.y })

    setLines([
      ...lines,
      {
        tool,
        points: [point.x, point.y],
        x: startPoint.x,
        y: startPoint.y,
        scaleX,
        scaleY,
        skewX,
        skewY,
        rotation
      }
      // { tool, points: [startPoint.x, startPoint.y], x, y, scaleX, scaleY, skewX: 0, skewY: 0, rotation }
    ])
  }

  const handleMouseMove = e => {
    if (!isDrawing.current) {
      return
    }
    const stage = e.target.getStage()
    const point = stage.getPointerPosition()
    const lastLine = lines[lines.length - 1]
    lastLine.points = lastLine.points.concat([point.x, point.y])
    lines.splice(lines.length - 1, 1, lastLine)
    setLines(lines.concat())
  }

  const handleMouseUp = () => {
    isDrawing.current = false
  }

  useEffect(() => {
    // groupRef.current.cache()
    console.log('🚀 ~ View ~ lines:', lines)
  }, [lines])

  // transform
  const [selectedShape, setSelectedShape] = useState(null)
  const transformerRef = useRef(null)
  const handleStageClick = e => {
    // clear
    if (e.target === e.target.getStage()) {
      setSelectedShape(null)
      return
    }
    if (e.target.nodeType === 'Shape') {
      setSelectedShape(groupRef.current)
      // 禁止旋转
      // transformerRef.current.rotationEnabled(false)
    }
  }

  return (
    <div>
      <select
        value={tool}
        onChange={e => {
          setTool(e.target.value)
        }}
      >
        <option value='pen'>Pen</option>
        <option value='eraser'>Eraser</option>
      </select>
      <Stage
        ref={stageRef}
        width={window.innerWidth}
        height={window.innerHeight}
        onMouseDown={handleMouseDown}
        onMousemove={handleMouseMove}
        onMouseup={handleMouseUp}
        onClick={handleStageClick}
      >
        <Layer>
          <Group ref={groupRef} draggable>
            {lines.map((line, i) => (
              <Line
                key={i}
                x={line.x}
                y={line.y}
                scaleX={line.scaleX}
                scaleY={line.scaleY}
                skewX={line.skewX}
                skewY={line.skewY}
                rotation={line.rotation}
                points={line.points}
                stroke='#df4b26'
                strokeWidth={10}
                tension={0.5}
                lineCap='round'
                lineJoin='round'
                globalCompositeOperation={line.tool === 'eraser' ? 'destination-out' : 'source-over'}
              />
            ))}
          </Group>
          {selectedShape && (
            <Transformer
              ref={transformerRef}
              boundBoxFunc={(oldBox, newBox) => {
                if (newBox.width < 5 || newBox.height < 5) {
                  return oldBox
                }
                return newBox
              }}
              nodes={[selectedShape]}
            />
          )}
        </Layer>
      </Stage>
    </div>
  )
}
